package cn.itsub;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

import cn.itsub.sodo.core.types.Vec2;

public class TestProgressBar {
	
	/**
	 * 进度条
	 * 例：rate.x=0.3,rate.y=0.4代表：图片宽度的70%和高度的60%大小的矩形范围会初始显示，以mid为中心，其余不显示的地方会根据百分比逐渐显示
	 * @param image 原始图片
	 * @param mid 中心点，从这里开始扩散，范围0-1
	 * @param rate 初始不显示的部分，x和y的取值范围都是0-1		
	 * @param progress 进度，范围0-1
	 * @return
	 */
	public static BufferedImage exe(BufferedImage image, Vec2 mid, Vec2 rate, float progress) {
		
		final int w = image.getWidth();
		final int h = image.getHeight();
		BufferedImage bufferedImage = new BufferedImage(w, h, BufferedImage.TYPE_4BYTE_ABGR);
		
		Vec2 p = new Vec2(w*mid.x, h*mid.y); //从这里开始扩散
		
		final float lenw = (1-rate.x) * w; //初始显示的宽度
		final float lenh = (1-rate.y) * h; //初始显示的高度
		Vec2 pm = new Vec2(Math.max(0, p.x-lenw/2),Math.max(0, p.y-lenh/2)); //初始左上角坐标
		Vec2 pn = new Vec2(Math.min(w, p.x+lenw/2),Math.min(h, p.y+lenh/2)); //初始右下角坐标
		Vec2 p1 = new Vec2(pm.x*(1-progress), pm.y*(1-progress));
		Vec2 p2 = new Vec2(pn.x+(w-pn.x)*progress,pn.y+(h-pn.y)*progress);
		
		for (int y = 0; y < h; y++) {
			for (int x = 0; x < w; x++) {
				int rgb = image.getRGB(x, y);
				int alpha=(x>=p1.x&&x<=p2.x&&y>=p1.y&&y<=p2.y)? 254:0;
				rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff);
				bufferedImage.setRGB(x, y, rgb);
			}
		}
		return bufferedImage;
	}

	public static void main(String[] args) throws IOException {
		
		init();
	}
	
	public static void init(){
		final JFrame fr = new JFrame();
		fr.setSize(800, 600);
		fr.setVisible(true);
		fr.setLocationRelativeTo(null);

		final JPanel jp = new JPanel() {
			float deg = 0;
			public void paint(Graphics g) {
				super.paintComponent(g);
				BufferedImage image;
				try {
					image = ImageIO.read(new File("D:/data/三国截图/QQ截图20201015001643.png"));
					deg+=0.01;
					if(deg>1){
						deg=0;
					}
					g.drawImage(exe(image,new Vec2(0f,0.5f),new Vec2(1,0),deg), 10, 10, null);
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		};

		new Timer().schedule(new TimerTask() {
			public void run() {
				jp.repaint();
			}
		}, 0, 10);

		fr.setContentPane(jp);
		fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
	}
}
